package alva.com.getcamera.view.fragment;


import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.hardware.Camera;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import alva.com.getcamera.R;
import alva.com.getcamera.utils.CameraUtils;
import alva.com.getcamera.utils.FileOperateUtil;

import static alva.com.getcamera.R.id.view_focus;

/**
 * A simple {@link Fragment} subclass.
 */
public class MainFragment extends Fragment implements View.OnClickListener, CompoundButton.OnCheckedChangeListener, View.OnTouchListener, Camera.AutoFocusCallback {
    private FrameLayout frameLayout;
    private View focusView;
    private SurfaceView surfaceView;
    private Button takePic;
    private Button takeVideo;
    private TextView videoTime;
    private ImageView cameraSwitch;
    public static ImageView cameraChange;
    public static ImageView setting;
    private ImageView settingBack;
    public static LinearLayout settingView;
    private Switch screenOn;
    private Switch shutter;
    private TextView flash;
    private TextView previewQuality;
    private Switch whiteBalance;
    private TextView picQuality;
    private TextView picSize;
    private TextView videoQuality;
    private TextView videoSize;

    private Camera camera;
    private Camera.Parameters parameters = null;
    private SurfaceHolder mSurfaceHolder = null;
    private MediaRecorder mediaRecorder = null;

    //设置视频录制的时间
    private int hour = 0;
    private int minute = 0;
    private int second = 0;

    private boolean bool;

    //是否是拍照模式下:true表示是拍照模式,false表示不是拍照模式
    private boolean isPicture = true;

    private boolean isPreview;
    //是否录制的标识:true表示不在录制,点击录制;false表示正在录制,点击暂停
    private boolean isRecording = true;

    //启动前置还是后置摄像头
    private int cameraPosition;

    public SharedPreferences cameraSharedPreference;
    public SharedPreferences.Editor editor;

    private boolean isScreenOn;

    private boolean isShutter = true;

    private String flashMode;
    private String flashModelString;
    private int flashModelInt;

    private int previewFrameRate;
    private String previewFrameQualityString;
    private int previewFrameQualityInt;

    private int pictureWidth;
    private int pictureHeight;
    private int pictureSizeInt;

    private int pictureQuality;
    private String pictureQualityString;
    private int pictureQualityInt;

    private boolean isAutoWhiteBalance;

    /**
     * 模式 NONE：无 FOCUSING：正在聚焦. FOCUSED:聚焦成功 FOCUSFAIL：聚焦失败
     */
    private enum MODE {
        NONE, FOCUSING, FOCUSED, FOCUSFAIL
    }

    public static boolean isSettingOn = false;

    private MODE mode = MODE.NONE;// 默认模式

    private Handler handler = new Handler();
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (bool) {
                handler.postDelayed(this, 1000);
                second++;
                if (second >= 60) {
                    minute++;
                    second = second % 60;
                }
                if (minute >= 60) {
                    hour++;
                    minute = minute % 60;
                }
                videoTime.setText(timeFormat(hour) + ":" + timeFormat(minute) + ":" + timeFormat(second));
            }
        }
    };

    public MainFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_main, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        viewInit(view);
        cameraSharedPreference = getContext().getSharedPreferences("camera_setting", Context.MODE_PRIVATE);
        editor = cameraSharedPreference.edit();
        cameraPosition = cameraSharedPreference.getInt("camera_position", 1);

        isScreenOn = cameraSharedPreference.getBoolean("screen_on", false);
        flashMode = cameraSharedPreference.getString("flash_mode", "auto");
        flashModelInt = cameraSharedPreference.getInt("flash_mode_int", 0);
        flashModelString = cameraSharedPreference.getString("flash_mode_string", "自动");

        previewFrameRate = cameraSharedPreference.getInt("preview_frame_quality", 22);
        previewFrameQualityInt = cameraSharedPreference.getInt("preview_frame_quality_int", 1);
        previewFrameQualityString = cameraSharedPreference.getString("preview_frame_quality_string", "较高");

        pictureWidth = cameraSharedPreference.getInt("preview_pic_width", 1920);
        pictureHeight = cameraSharedPreference.getInt("preview_pic_height", 1080);
        pictureSizeInt = cameraSharedPreference.getInt("preview_pic_int", 1);

        pictureQuality = cameraSharedPreference.getInt("picture_quality", 90);
        pictureQualityString = cameraSharedPreference.getString("picture_quality_string", "较高");
        pictureQualityInt = cameraSharedPreference.getInt("picture_quality_int", 1);

        isAutoWhiteBalance = cameraSharedPreference.getBoolean("auto_balance", false);

        previewInit(isScreenOn);

        previewQuality.setText(previewFrameQualityString);
        screenOn.setChecked(isScreenOn);
        flash.setText(flashModelString);
        picSize.setText(pictureWidth + "x" + pictureHeight);
        picQuality.setText(pictureQualityString);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.cameraSwitch:
                if (isPicture) {//拍照模式下切换至摄像模式
                    takePic.setVisibility(View.INVISIBLE);
                    takeVideo.setVisibility(View.VISIBLE);
                    cameraSwitch.setImageResource(R.mipmap.camera);
                    videoTime.setVisibility(View.VISIBLE);
                    isPicture = false;
                } else {//摄像模式下切换至拍照模式
                    stopRecordVideo();
                    takeVideo.setVisibility(View.INVISIBLE);
                    takePic.setVisibility(View.VISIBLE);
                    cameraSwitch.setImageResource(R.mipmap.video);
                    videoTime.setVisibility(View.INVISIBLE);
                    videoTime.setText("00:00:00");
                    isPicture = true;
                }
                break;
            case R.id.takePic:
                if (mediaRecorder != null) {
                    mediaRecorder.stop();
                    mediaRecorder.release();
                    mediaRecorder = null;
                    isRecording = true;
                }
                if (camera == null) {
                    cameraInit(cameraPosition, previewFrameRate, flashMode, pictureWidth, pictureHeight, isAutoWhiteBalance);
                } else {
                    camera.takePicture(null, null, new MyPictureCallback());
                }
                break;
            case R.id.takeVideo:
                if (isRecording) {//表示不在录制,点击录制
                    //点击录制需要结束预览
                    if (isPreview) {
                        camera.stopPreview();
                        camera.release();
                        camera = null;
                        cameraInit(cameraPosition, previewFrameRate, flashMode, pictureWidth, pictureHeight, isAutoWhiteBalance);
                    }
                    hour = 0;
                    minute = 0;
                    second = 0;
                    bool = true;
                    if (mediaRecorder == null) {
                        mediaRecorder = new MediaRecorder();
                    } else {
                        mediaRecorder.reset();
                    }
                    if (camera != null) {
                        camera.unlock();
                        mediaRecorder.setCamera(camera);
                    }
                    mediaRecorderInit();
                    try {
                        mediaRecorder.prepare();
                        takeVideo.setBackgroundResource(R.mipmap.player_stop);
                        handler.postDelayed(runnable, 1000);
                        videoTime.setText(timeFormat(hour) + ":" + timeFormat(minute) + ":" + timeFormat(second));
                        mediaRecorder.start();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    isRecording = false;
                } else {
                    stopRecordVideo();
                }
                break;
            case R.id.camera_change:
//                int cameraNum = 0;
//                Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
//                cameraNum = Camera.getNumberOfCameras();
//                for (int i = 0; i < cameraNum; i++) {
//                    Camera.getCameraInfo(i, cameraInfo);
//                    if (cameraPosition == 1) {//当前摄像头是后置,切换至前置
//                        if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
//                            camera.stopPreview();
//                            camera.release();
//                            camera = null;
//                            isPreview = false;
//                            cameraInit(i, previewFrameRate, flashMode, pictureWidth, pictureHeight, isAutoWhiteBalance);
//                            try {
//                                camera.setPreviewDisplay(mSurfaceHolder);
//                            } catch (IOException e) {
//                                e.printStackTrace();
//                            }
//                            camera.startPreview();
//                            isPreview = true;
//                            cameraPosition = 0;
//                            editor.putInt("camera_position", cameraPosition);
//                            editor.commit();
//                            break;
//                        }
//                    } else {
//                        if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
//                            camera.stopPreview();
//                            camera.release();
//                            camera = null;
//                            isPreview = false;
//                            cameraInit(i, previewFrameRate, flashMode, pictureWidth, pictureHeight, isAutoWhiteBalance);
//                            try {
//                                camera.setPreviewDisplay(mSurfaceHolder);
//                            } catch (IOException e) {
//                                e.printStackTrace();
//                            }
//                            camera.startPreview();
//                            isPreview = true;
//                            cameraPosition = 1;
//                            editor.putInt("camera_position", cameraPosition);
//                            editor.commit();
//                            break;
//                        }
//                    }
//                }
                break;
            case R.id.setting:
                settingView.setVisibility(View.VISIBLE);
                setting.setVisibility(View.INVISIBLE);
                cameraChange.setVisibility(View.INVISIBLE);
                isSettingOn = true;
                break;
            case R.id.setting_back:
                settingView.setVisibility(View.GONE);
                setting.setVisibility(View.VISIBLE);
                cameraChange.setVisibility(View.VISIBLE);
                isSettingOn = false;
                break;
            case R.id.flashLight:
                createFlashModeDialog(R.array.flashMode, "设置闪光灯模式", flashModelInt, flash);
                break;
            case R.id.previewRate:
                createPreviewRateDialog(R.array.previewFrameRate, "设置图片分辨率", previewFrameQualityInt, previewQuality);
                break;
            case R.id.pictureQuality:
                createPictureQualityDialog(R.array.pictureQuality, "设置相片质量", pictureQualityInt, picQuality);
                break;
            case R.id.pictureSize:
                createPictureSizeDialog(CameraUtils.get16And9PictureSizes(camera), "设置分辨率", pictureSizeInt, picSize);
                break;
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.screenOn:
                surfaceView.setKeepScreenOn(isChecked);
                isScreenOn = isChecked;
                editor.putBoolean("screen_on", isScreenOn);
                editor.commit();
                screenOn.setChecked(isScreenOn);
                break;
            case R.id.shutterVoice:

                break;
            case R.id.whiteBalance:
                isAutoWhiteBalance = isChecked;
                parameters.remove("auto-whitebalance-lock");
                parameters.setAutoWhiteBalanceLock(isAutoWhiteBalance);
                camera.setParameters(parameters);
                editor.putBoolean("auto_balance", isAutoWhiteBalance);
                editor.commit();
                whiteBalance.setChecked(isAutoWhiteBalance);
                break;
        }
    }

    private void viewInit(View view) {
        frameLayout = (FrameLayout) view.findViewById(R.id.frameLayout);
        focusView = view.findViewById(view_focus);
        surfaceView = (SurfaceView) view.findViewById(R.id.surfaceViewPic);
        takePic = (Button) view.findViewById(R.id.takePic);
        takeVideo = (Button) view.findViewById(R.id.takeVideo);
        videoTime = (TextView) view.findViewById(R.id.videoTime);
        cameraSwitch = (ImageView) view.findViewById(R.id.cameraSwitch);
        cameraChange = (ImageView) view.findViewById(R.id.camera_change);
        setting = (ImageView) view.findViewById(R.id.setting);
        settingView = (LinearLayout) view.findViewById(R.id.camera_setting);
        settingBack = (ImageView) view.findViewById(R.id.setting_back);
        screenOn = (Switch) view.findViewById(R.id.screenOn);
        shutter = (Switch) view.findViewById(R.id.shutterVoice);
        flash = (TextView) view.findViewById(R.id.flashLight);
        previewQuality = (TextView) view.findViewById(R.id.previewRate);
        whiteBalance = (Switch) view.findViewById(R.id.whiteBalance);
        picQuality = (TextView) view.findViewById(R.id.pictureQuality);
        picSize = (TextView) view.findViewById(R.id.pictureSize);
        videoQuality = (TextView) view.findViewById(R.id.videoRate);
        videoSize = (TextView) view.findViewById(R.id.videoSize);

        frameLayout.setOnTouchListener(this);

        takePic.setOnClickListener(this);
        takeVideo.setOnClickListener(this);
        cameraSwitch.setOnClickListener(this);
        cameraChange.setOnClickListener(this);
        setting.setOnClickListener(this);
        settingBack.setOnClickListener(this);
        flash.setOnClickListener(this);
        previewQuality.setOnClickListener(this);
        picQuality.setOnClickListener(this);
        picSize.setOnClickListener(this);
        videoQuality.setOnClickListener(this);
        videoSize.setOnClickListener(this);

        shutter.setOnCheckedChangeListener(this);
        screenOn.setOnCheckedChangeListener(this);
        whiteBalance.setOnCheckedChangeListener(this);

    }

    private void createFlashModeDialog(int itemArray, String title, int level, final View view) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle(title);
        builder.setSingleChoiceItems(itemArray, level, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 0:
                        flashMode = "auto";
                        flashModelString = "自动";
                        flashModelInt = 0;
                        break;
                    case 1:
                        flashMode = "off";
                        flashModelString = "关闭";
                        flashModelInt = 1;
                        break;
                }
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                editor.putString("flash_mode", flashMode);
                editor.putString("flash_mode_string", flashModelString);
                editor.putInt("flash_mode_int", flashModelInt);
                editor.commit();
                parameters.remove("flash-mode");
                parameters.setFlashMode(flashMode);
                camera.setParameters(parameters);
                ((TextView) view).setText(flashModelString);
            }
        });
        builder.setCancelable(false);
        builder.show();
    }

    private void createPreviewRateDialog(int itemArray, String title, int level, final View view) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle(title);
        builder.setSingleChoiceItems(itemArray, level, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 0:
                        previewFrameRate = 30;
                        previewFrameQualityString = "最高";
                        previewFrameQualityInt = 0;
                        break;
                    case 1:
                        previewFrameRate = 22;
                        previewFrameQualityString = "较高";
                        previewFrameQualityInt = 1;
                        break;
                    case 2:
                        previewFrameRate = 15;
                        previewFrameQualityString = "普通";
                        previewFrameQualityInt = 2;
                        break;
                    case 3:
                        previewFrameRate = 8;
                        previewFrameQualityString = "最低";
                        previewFrameQualityInt = 3;
                        break;
                }
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                editor.putInt("preview_frame_quality", previewFrameRate);
                editor.putString("preview_frame_quality_string", previewFrameQualityString);
                editor.putInt("preview_frame_quality_int", previewFrameQualityInt);
                editor.commit();
                parameters.remove("preview-frame-rate");
                parameters.setPreviewFrameRate(previewFrameRate);
                camera.setParameters(parameters);
                ((TextView) view).setText(previewFrameQualityString);
            }
        });
        builder.setCancelable(false);
        builder.show();
    }

    private void createPictureQualityDialog(int itemArray, String title, int level, final View view) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle(title);
        builder.setSingleChoiceItems(itemArray, level, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 0:
                        pictureQuality = 100;
                        pictureQualityString = "最高";
                        pictureQualityInt = 0;
                        break;
                    case 1:
                        pictureQuality = 90;
                        pictureQualityString = "高";
                        pictureQualityInt = 1;
                        break;
                    case 2:
                        pictureQuality = 60;
                        pictureQualityString = "普通";
                        pictureQualityInt = 2;
                        break;
                    case 3:
                        pictureQuality = 30;
                        pictureQualityString = "低";
                        pictureQualityInt = 3;
                        break;
                }
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                editor.putInt("picture_quality", pictureQuality);
                editor.putString("picture_quality_string", pictureQualityString);
                editor.putInt("picture_quality_int", pictureQualityInt);
                editor.commit();
                parameters.remove("jpeg-quality");
                parameters.setJpegQuality(pictureQuality);
                camera.setParameters(parameters);
                ((TextView) view).setText(pictureQualityString);
            }
        });
        builder.setCancelable(false);
        builder.show();
    }

    private void createPictureSizeDialog(final String[] itemArray, String title, int level, final View view) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle(title);
        builder.setSingleChoiceItems(itemArray, level, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 0:
                        pictureWidth = Integer.parseInt(itemArray[which].substring(0, itemArray[which].indexOf("x")));
                        pictureHeight = Integer.parseInt(itemArray[which].substring(itemArray[which].indexOf("x") + 1));
                        pictureSizeInt = 0;
                        break;
                    case 1:
                        pictureWidth = Integer.parseInt(itemArray[which].substring(0, itemArray[which].indexOf("x")));
                        pictureHeight = Integer.parseInt(itemArray[which].substring(itemArray[which].indexOf("x") + 1));
                        pictureSizeInt = 1;
                        break;
                    case 2:
                        pictureWidth = Integer.parseInt(itemArray[which].substring(0, itemArray[which].indexOf("x")));
                        pictureHeight = Integer.parseInt(itemArray[which].substring(itemArray[which].indexOf("x") + 1));
                        pictureSizeInt = 2;
                        break;
                }
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                editor.putInt("preview_pic_width", pictureWidth);
                editor.putInt("preview_pic_height", pictureHeight);
                editor.putInt("preview_pic_int", pictureSizeInt);
                editor.commit();
                parameters.remove("picture-size");
                parameters.remove("preview-size");
                parameters.setPictureSize(pictureWidth, pictureHeight);
                parameters.setPreviewSize(pictureWidth, pictureHeight);
                camera.setParameters(parameters);
                ((TextView) view).setText(pictureWidth + "x" + pictureHeight);
            }
        });
        builder.setCancelable(false);
        builder.show();
    }

    @Override
    public void onPause() {
        super.onPause();
        if (camera != null) {
            camera.stopPreview();
            camera.release();
            camera = null;
            isPreview = false;
        }
        if (mediaRecorder != null) {
            mediaRecorder.stop();
            mediaRecorder.release();
            mediaRecorder = null;
            takeVideo.setBackgroundResource(R.drawable.takepic_button_shape);
            isRecording = true;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (camera == null) {
            cameraInit(cameraPosition, previewFrameRate, flashMode, pictureWidth, pictureHeight, isAutoWhiteBalance);
        }
        try {
            camera.setPreviewDisplay(mSurfaceHolder);
            camera.startPreview();
            isPreview = true;
            isRecording = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void previewInit(boolean isScreenOn) {
        //设置surfaceView数据来源的类型
        //surfaceView.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        //设置surfaceView的分辨率
//        surfaceView.getHolder().setFixedSize(640, 480);
//        ViewGroup.LayoutParams params = surfaceView.getLayoutParams();
//        params.height = DensityUtil.dip2px(getActivity(), CameraUtils.findBestPreviewSize(camera).width);
//        params.width = DensityUtil.dip2px(getActivity(), CameraUtils.findBestPreviewSize(camera).height);
//        surfaceView.setLayoutParams(params);
        //设置屏幕长亮
        surfaceView.setKeepScreenOn(isScreenOn);
        surfaceView.getHolder().addCallback(new SurfaceCallback());
    }

    private void cameraInit(int cameraPosition, int previewFrameRate, String flashMode, int pictureWidth, int pictureHeight, boolean isAutoWhiteBalance) {
        if (camera == null) {
            camera = Camera.open();
            parameters = camera.getParameters();
            parameters.setPreviewFrameRate(previewFrameRate); // 每秒20帧有效范围[8,30]
            parameters.setPictureFormat(PixelFormat.JPEG);// 设置照片的输出格式
            parameters.setJpegQuality(80);
            parameters.setPictureSize(pictureWidth, pictureHeight);
            parameters.setPreviewSize(CameraUtils.findBestPreviewSize(camera).width, CameraUtils.findBestPreviewSize(camera).height);
            parameters.setJpegThumbnailSize(200, 200);
            parameters.setJpegThumbnailQuality(80);
            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
            parameters.setAutoWhiteBalanceLock(isAutoWhiteBalance);
            parameters.setVideoStabilization(true);//拍摄视频防抖
            parameters.setRecordingHint(true);
            parameters.setFlashMode(flashMode);
            camera.setDisplayOrientation(90);
            camera.setParameters(parameters);
        }
    }

    private void mediaRecorderInit() {
        //设置音频录制源
        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        //设置视频录制源
        mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
        //设置录制完成后的视频格式为".mp4"
        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        //设置音频录制的编码
        mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
        //设置视频录制的编码
        mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
        //设置视频的帧率
        mediaRecorder.setVideoFrameRate(30);
        mediaRecorder.setOrientationHint(90);
        //设置视频的大小
        mediaRecorder.setVideoSize(640, 480);
        mediaRecorder.setVideoEncodingBitRate(3 * 1024 * 1024);
        mediaRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());
        mediaRecorder.setOutputFile(FileOperateUtil.setFileSavedFile("/myVideo/", ".mp4").getAbsolutePath());
    }

    private String timeFormat(int time) {
        String s = time + "";
        if (s.length() == 1) {
            s = "0" + s;
        }
        return s;
    }

    private void stopRecordVideo() {
        if (mediaRecorder != null) {
            //点击停止录像,并保存文件
            mediaRecorder.stop();
            videoTime.setText(timeFormat(hour) + ":" + timeFormat(minute) + ":" + timeFormat(second));
            mediaRecorder.release();
            mediaRecorder = null;
            camera.release();
            camera = null;
        }
        bool = false;
        takeVideo.setBackgroundResource(R.drawable.takevideo_button_shape);
        isRecording = true;
        cameraInit(cameraPosition, previewFrameRate, flashMode, pictureWidth, pictureHeight, isAutoWhiteBalance);
        try {
            camera.startPreview();
            camera.cancelAutoFocus();
            camera.setPreviewDisplay(mSurfaceHolder);
        } catch (IOException e) {
            e.printStackTrace();
        }
        isPreview = true;
    }

    private class SurfaceCallback implements SurfaceHolder.Callback {

        /**
         * 开始拍照时调用
         * 初始化一些数据
         *
         * @param surfaceHolder
         */
        @Override
        public void surfaceCreated(SurfaceHolder surfaceHolder) {
            mSurfaceHolder = surfaceHolder;
            cameraInit(cameraPosition, previewFrameRate, flashMode, pictureWidth, pictureHeight, isAutoWhiteBalance);
            try {
                camera.setPreviewDisplay(mSurfaceHolder);
                camera.startPreview();
                camera.cancelAutoFocus();
                isPreview = true;
                isRecording = true;
            } catch (IOException e) {
                e.printStackTrace();
                camera.release();
                camera = null;
            }
        }

        /**
         * 拍照状态发生变化
         *
         * @param surfaceHolder
         * @param i
         * @param width
         * @param height
         */
        @Override
        public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int width, int height) {
            mSurfaceHolder = surfaceHolder;
        }

        /**
         * 拍照结束
         *
         * @param surfaceHolder
         */
        @Override
        public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
            if (camera != null) {
                if (isPreview) {
                    camera.stopPreview();
                    camera.release();
                    mediaRecorder.stop();
                    mediaRecorder.release();
                    isPreview = false;
                    isRecording = true;
                }
                camera = null;
                mSurfaceHolder = null;
                mediaRecorder = null;
            }
        }
    }

    private class MyPictureCallback implements Camera.PictureCallback {

        /**
         * 拍照完成的回调方法
         *
         * @param bytes
         * @param camera
         */
        @Override
        public void onPictureTaken(final byte[] bytes, Camera camera) {
            //存入SD卡中
            new Thread(new Runnable() {
                @Override
                public void run() {
                    FileOperateUtil.savePicture(bytes);
                }
            }).start();
            camera.startPreview();
            camera.cancelAutoFocus();
            isPreview = true;
        }

    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            int width = focusView.getWidth();
            int height = focusView.getHeight();
            focusView.setBackgroundResource(R.mipmap.ic_focus_focusing);
            focusView.setX(event.getX() - (width / 2));
            focusView.setY(event.getY() - (height / 2));
        } else {
            mode = MODE.FOCUSING;
            focusOnTouch(event);
        }
        return true;
    }

    /**
     * 设置焦点和测光区域
     *
     * @param event
     */
    public void focusOnTouch(MotionEvent event) {

        int[] location = new int[2];
        frameLayout.getLocationOnScreen(location);

        Rect focusRect = calculateTapArea(focusView.getWidth(),
                focusView.getHeight(), 1f, event.getRawX(), event.getRawY(),
                location[0], location[0] + frameLayout.getWidth(), location[1],
                location[1] + frameLayout.getHeight());
        Rect meteringRect = calculateTapArea(focusView.getWidth(),
                focusView.getHeight(), 1.5f, event.getRawX(), event.getRawY(),
                location[0], location[0] + frameLayout.getWidth(), location[1],
                location[1] + frameLayout.getHeight());

        Camera.Parameters parameters = camera.getParameters();
        parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);

        // System.out.println("CustomCameraView getMaxNumFocusAreas = " +
        // parameters.getMaxNumFocusAreas());
        if (parameters.getMaxNumFocusAreas() > 0) {
            List<Camera.Area> focusAreas = new ArrayList<Camera.Area>();
            focusAreas.add(new Camera.Area(focusRect, 1000));

            parameters.setFocusAreas(focusAreas);
        }

        // parameters.getMaxNumMeteringAreas());
        if (parameters.getMaxNumMeteringAreas() > 0) {
            List<Camera.Area> meteringAreas = new ArrayList<Camera.Area>();
            meteringAreas.add(new Camera.Area(meteringRect, 1000));

            parameters.setMeteringAreas(meteringAreas);
        }

        try {
            camera.setParameters(parameters);
        } catch (Exception e) {
        }
        camera.autoFocus(this);
    }

    /**
     * 计算焦点及测光区域
     *
     * @param focusWidth
     * @param focusHeight
     * @param areaMultiple
     * @param x
     * @param y
     * @param previewleft
     * @param previewRight
     * @param previewTop
     * @param previewBottom
     * @return Rect(left, top, right, bottom) : left、top、right、bottom是以显示区域中心为原点的坐标
     */
    public Rect calculateTapArea(int focusWidth, int focusHeight,
                                 float areaMultiple, float x, float y, int previewleft,
                                 int previewRight, int previewTop, int previewBottom) {
        int areaWidth = (int) (focusWidth * areaMultiple);
        int areaHeight = (int) (focusHeight * areaMultiple);
        int centerX = (previewleft + previewRight) / 2;
        int centerY = (previewTop + previewBottom) / 2;
        double unitx = ((double) previewRight - (double) previewleft) / 2000;
        double unity = ((double) previewBottom - (double) previewTop) / 2000;
        int left = clamp((int) (((x - areaWidth / 2) - centerX) / unitx),
                -1000, 1000);
        int top = clamp((int) (((y - areaHeight / 2) - centerY) / unity),
                -1000, 1000);
        int right = clamp((int) (left + areaWidth / unitx), -1000, 1000);
        int bottom = clamp((int) (top + areaHeight / unity), -1000, 1000);

        return new Rect(left, top, right, bottom);
    }

    public int clamp(int x, int min, int max) {
        if (x > max)
            return max;
        if (x < min)
            return min;
        return x;
    }

    @Override
    public void onAutoFocus(boolean success, Camera camera) {
// System.out.println("CustomCameraView onAutoFocus success = " +
        // success);
        if (success) {
            mode = MODE.FOCUSED;
            // Camera.Parameters parameters = _camera.getParameters();
            // float[] output = new float[3];
            // parameters.getFocusDistances(output);
            // List<Camera.Area> area = parameters.getFocusAreas();
            // Rect rect = area.get(0).rect;
            //
            // System.out.println("CustomCameraView onAutoFocus output1 = " +
            // output[1] + " ,output[2] = " + output[2] + " ,output[3]" +
            // output[2]);
            // System.out.println("CustomCameraView onAutoFocus rect.top = " +
            // rect.top + " , rect.left = " + rect.left + " ,rect.right" +
            // rect.right
            // +
            // " ,rect.bottom" + rect.bottom);
            focusView.setBackgroundResource(R.mipmap.ic_focus_focused);
        } else {
            mode = MODE.FOCUSFAIL;
            focusView.setBackgroundResource(R.mipmap.ic_focus_failed);
        }
        setFocusView();
    }

    private void setFocusView() {
        new Handler().postDelayed(new Runnable() {

            @SuppressWarnings("deprecation")
            @Override
            public void run() {
                focusView.setBackgroundDrawable(null);
            }
        }, 1 * 1000);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            camera.setDisplayOrientation(90);
        } else {
            camera.setDisplayOrientation(90);
        }
    }
}
